import { message } from '@src/util/message'
import { NodeTypeEnum, AllNodeType } from '@src/modules/trigger/model/enum/cell.ts'
import state from '@src/modules/trigger/view/setting/util/state.js'
/* hook */
import { getNodeType } from '@src/modules/trigger/utils/index.ts'

// 执行动作校验方法
export function valExec(currentNode, currentCtx) {
  // 关闭之前进行必填校验
  const { appId = '', apiId = '', apiAction = '', fieldOptions = {} } = currentNode?.options || {};

  // 如果 appId 或 apiId 不存在，设置 requiredCheck 为 false 并返回
  if (!appId || !apiId) {
    currentCtx.$set(currentNode.options, 'requiredCheck', false);
    return;
  }

  // 定义一个函数来设置 requiredCheck
  const setRequiredCheck = value => {
    currentCtx.$set(currentNode.options, 'requiredCheck', value);
  };

  // 定义一个函数来检查列表中的项是否满足条件
  const checkList = (list, condition) => {
    return list.some(item => condition(item));
  };

  if (apiAction === 'DELETE') {
    const deleteList = fieldOptions?.delete || [];
    const message = fieldOptions?.message || fieldOptions?.message?.paasReceiver || '';
    const condition = item => item?.toEnName && item?.operate && item?.valueType && item?.value[0];
    setRequiredCheck(checkList(deleteList, condition) && !!message);
    return;
  }

  if (apiAction === 'UPDATE') {
    const selectList = fieldOptions?.select || [];
    if (selectList.length > 0) {
      // TODO item.value 这里的数据结构存疑，待后端问问[x,x]
      const selectCondition = item => item?.toEnName && item?.operate && item?.valueType && item?.value[0];
      setRequiredCheck(checkList(selectList, selectCondition));
      return;
    } else {
      setRequiredCheck(true);
      return
    }
  }

  if (apiAction === 'INSERT') {
    if (fieldOptions && Reflect.has(fieldOptions, 'convertType') && fieldOptions.convertType === 'code') {
      setRequiredCheck(true);
      return;
    }
    const insertList = fieldOptions?.insert || [];
    const allRequiredCondition = item => (item?.required ? item?.valueType && item?.value[0] : true);
    setRequiredCheck(insertList.every(allRequiredCondition));
    return;
  }

  if (apiAction === 'SELECT') {
    if (fieldOptions && Reflect.has(fieldOptions, 'convertType') && fieldOptions.convertType === 'code') {
      setRequiredCheck(true);
      return;
    }
    const insertList = fieldOptions?.insert || [];
    const allRequiredCondition = item => (item?.required ? item?.valueType && item?.value[0] : true);
    setRequiredCheck(insertList.every(allRequiredCondition));
    return;
  }

  setRequiredCheck(false);
}

/**
 * @description 校验消息方法
 */
export function valMessage(currentNode, currentCtx) {
  const setRequiredCheck = value => {
    currentCtx.$set(currentNode.options, 'requiredCheck', value);
  };
  if (currentNode.options &&  Reflect.has(currentNode.options, 'fieldOptions')) {
    setRequiredCheck(true)
    return
  } else {
    setRequiredCheck(false)
    return
  }
}

/**
 * @description 校验条件节点方法
 * @param currentNode 
 * @param currentCtx 
 */
export function valCondition(currentNode, currentCtx) {
  const setRequiredCheck = value => {
    currentCtx.$set(currentNode.options, 'requiredCheck', value);
  }
  // 如果条件节点下面的children为空,requiredCheck为false 校验不通过
  if (Reflect.has(currentNode, 'children') && currentNode.children.length === 0) {
    setRequiredCheck(false)
    return
  } else {
    setRequiredCheck(true)
    return
  }
}

/**
 * @description 允许校验方法
 */
export function runVail(data, currentCtx) {
    if (!data) return
    // 将当前树形结构数据全部执行一遍
    data?.forEach(item => {
        if ([NodeTypeEnum.NODE].includes(currentTypeUtils(item))) {
            valExec(item, currentCtx)
        }
        if ('message' === currentTypeUtils(item)) {
          valMessage(item, currentCtx)
        }
        if ('condition-node' === currentTypeUtils(item)) {
          valCondition(item, currentCtx)
        }
        if (item?.children && item?.children?.length) {
            runVail(item.children, currentCtx)
        }
    })
}


/**
 * @description 判断具有校验的的节点函数，如果未校验成功，返回false
 * @returns {boolean} 校验成功true 校验失败false
 */

export function checkRequiredNodeList(data) {
  if (!data) return [];

  const requiredCheckStatuses = [] as Boolean[];
  const requiredCheckCondition = [] as Boolean[];

  function checkNodes(nodes) {
      for (const item of nodes) {
          if ([NodeTypeEnum.NODE].includes(currentTypeUtils(item))) {
              if (Reflect.has(item.options, 'requiredCheck')) {
                  requiredCheckStatuses.push(item.options.requiredCheck);
              }
          }
          if (currentTypeUtils(item) === 'message') {
            if (Reflect.has(item.options, 'requiredCheck')) {
              requiredCheckStatuses.push(item.options.requiredCheck);
            }
          }
          if (currentTypeUtils(item) === 'condition-node') {
            if (Reflect.has(item.options, 'requiredCheck')) {
              requiredCheckStatuses.push(item.options.requiredCheck);
              requiredCheckCondition.push(item.options.requiredCheck);
            }
          }
          if (item?.children && item?.children.length) {
              checkNodes(item.children);
          }
      }
  }

  checkNodes(data);
  return [requiredCheckStatuses, requiredCheckCondition];
}

export function validatedResult(data) {
  if (!data) return
  const [res, conditionRes] = checkRequiredNodeList(data)
  return {
    errNode: res.filter(item => item === false).length || 0,
    errCondition: conditionRes.filter(item => item === false).length || 0
  }
}

/**
 * @description 校验第一个节点信息
 * @param startNode 
 * @returns {Boolean} true 校验通过 false 校验不通过
 */
export function validateStartNode(startNode) {
  if (!startNode) return
  if (!Reflect.has(startNode.options, 'appId')) {
    message.error("请选择触发器开始节点应用")
    return false
  }
  if (!Reflect.has(startNode.options, 'apiId')) {
    message.error('请选择触发器开始节点的对象')
    return false
  }
  return true
}



function currentTypeUtils(nodeData) {
  return getNodeType(nodeData)
}